const express = require("express");//引入express框架
const app = express();//用常量app接收
const cors = require('cors')
const logger = require('morgan');
const bodyParser = require('body-parser');
const swaggerJSDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

// Swagger配置
const swaggerDefinition = {
  openapi: '3.0.0',
  info: {
    title: 'Resume API',
    version: '1.0.0',
    description: 'API文档',
  },
  servers: [
    {
      url: 'http://localhost:5000',
      description: '开发服务器',
    },
  ],
};

const options = {
  swaggerDefinition,
  apis: ['./router/**/*.js'],
};

const swaggerSpec = swaggerJSDoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

app.use(express.json()) // 接收前端json格式文件
// 配置cors中间件，允许所有来源的跨域请求
app.use(cors({
  origin: '*', // 允许所有来源
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 允许的HTTP方法
  allowedHeaders: ['Content-Type', 'Content-Length', 'Authorization', 'Accept', 'X-Requested-With']
})) // cors中间件处理跨域
app.use(express.urlencoded({extended: true}))  // 处理post请求数据格式问题
app.use(logger('dev'));
app.use(bodyParser.json());// 解析 JSON 请求体
// // 微信认证
const auth = require('./wechat/auth')
app.use(auth())

// 响应数据的中间件
app.use(function (req, res, next) {
    // status = 0 为成功； status = 1 为失败； 默认将 status 的值设置为 1，方便处理失败的情况
    res.cc = function (err, status = 1) {
        res.send({
            // 状态
            status,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            data: err instanceof Error ? err.message : err,
        })
    }
    next()
})
// app中所有接口响应格式处理
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild')
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8")
    res.header("Cache-Control", 'no-store')
    next()
})
const importRouter = require('./import/index'); // 引入导入路由的文件
const currentConfig=require('./config/envConfig')
app.use(importRouter);// 使用导入的路由
const logRouter = require('./router/logs/log');
app.use(logRouter);
// 启用信任代理设置
app.set('trust proxy', true);
app.listen(5000, "0.0.0.0", () => { //在 80 端口启动我们的服务
    console.log("server is running on port http://127.0.0.1:5000");
});